package com.example.beryl.proSystem;
/**
 * 完工报工页面 20230829
 */
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import android.app.AlertDialog;
import android.content.IntentFilter;
import android.os.Bundle;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.NormalProgressDialog;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.databinding.ActivityFinishWorkBinding;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.FWork.FBarcode;
import com.example.beryl.http.Net_finishWork;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.HashMap;
import java.util.List;

public class finishWork extends AppCompatActivity {
    ActivityFinishWorkBinding binding;
    public ConstraintLayout clMain;
    public static final int GC = 1;
    public static final int WareHouseCodeRc = 2;
    public static final int FCS = 3;
    public static final int Summit = 4;
    public boolean mReceiverTag = false;//广播注册标志
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();
    HandlePublic handlePublic = new HandlePublic();
    Net_finishWork net_finishWork = new Net_finishWork();
    FBarcode fBarcode = new FBarcode();
    boolean IsTopSummit = false;

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_finish_work);
        Toolbar toolbar = findViewById(R.id.toolbar);
        clMain = findViewById(R.id.cl_main);
        toolbar.setTitle("完工报工");
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back);
        toolbar.setNavigationOnClickListener(view -> finish());
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getGroupId()) {
            }
            return false;
        });

        mBroadcastReceiver.setScanHeadListener(getcode -> getBroadReceive(getcode));

        handlePublic.setGetResult((what, t) -> getHandle(what,t));

        binding.FinishSummit.setOnClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(finishWork.this);
            builder.setTitle("提示");
            builder.setMessage("是否提交数据");
            builder.setPositiveButton("是", (dialogInterface, i) -> CheckSummitData());
            builder.setNegativeButton("否",
                    (dialog, which) -> dialog.dismiss());
            builder.create().show();
        });
    }
    //得到仓库库位、仓库
    private void getWareHouseCode(String cProductDepNo) {
        //handlePublic.startLoad(finishWork.this);
        new Thread(() -> CommSelectMethod(Action.action.finishWareHouseCode,cProductDepNo,WareHouseCodeRc)).start();
    }
    //广播回调
    private void getBroadReceive(String code) {
        try {

            switch(code.substring(0,2))
            {
                case "WO":
                    binding.LCDFinish.setText(code);
                    //handlePublic.startLoad(finishWork.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getBarcode(code);
                        }
                    }).start();
                    break;
            }
        }catch (Exception e)
        {
            handlePublic.Alert(e.getMessage(),this);
        }
    }

    //数据库回调
    private void getHandle(int what, Object t) throws JSONException {
        List listgetData;
        // Gson gson = new Gson();
        listgetData= (List)t;
        String getlist = listgetData.get(0).toString();
        if (getlist.contains("[") || getlist.contains("{"))
        {
            switch (what)
            {
                case GC://流传单信息
                    getlist = handlePublic.JosnChange(getlist);
                    fBarcode = (FBarcode) handlePublic.getEntity(getlist,FBarcode.class);
                    //fBarcode = gson.fromJson(getlist,FBarcode.class);
                    binding.FinishPCNUM.setText(fBarcode.cMOLotNo);
                    binding.Custom.setText(fBarcode.cCusName);
                    //binding.LCDFinish.setText("WO-" + fBarcode.cMOLotNo);
                    getWareHouseCode(Action.loginUser.cProductDepNo);
                    break;
                case WareHouseCodeRc://入库仓库、入库货位
                    JSONArray jsonWare = new JSONArray(getlist);
                    binding.RuKuCang.setText(jsonWare.getJSONObject(0).get("入库仓库").toString());
                    binding.RuKuTag.setText(jsonWare.getJSONObject(0).get("入库货位").toString());
                    break;
                case FCS://提交检查回调
                    getlist = handlePublic.ChangeString(getlist);
                    if (getlist.contains("1"))//某工序有报工却正常情况下
                    {
                        SummitData();
                    }else//提示用户
                    {
                        showUpdateDialog(getlist);
                        if (IsTopSummit)
                        {
                            SummitData();
                        }
                    }
                    break;
                case Summit:
                    getlist = handlePublic.ChangeString(getlist);
                    if (getlist.contains("1"))
                    {
                        handlePublic.Alert("提交成功",this);
                        CleanForm();
                    }
                    break;
            }
        }
        else
        {
            handlePublic.Alert(getlist,this);
        }
    }

    //得到流传单信息
    private void getBarcode(String getcode) {
        CommSelectMethod(Action.action.finishWorkBarcode,getcode,GC);
    }

    /**
     * 数据提交检查
     */
    private void CheckSummitData() {
        HashMap<String,String> dic = new HashMap<>();
        dic.put("cMOLotNo",binding.FinishPCNUM.getText().toString());
        dic.put("cProductDepNo",Action.loginUser.cProductDepNo);
        dic.put("GNumber",binding.FinishNum.getText().toString());
        dic.put("ANumber",binding.buliangshu.getText().toString());
        if(dic.containsValue("")) {
            handlePublic.Alert("请把表格输入完整",this);
        }else
        {
            String json = handlePublic.MakeJson(dic);
            System.out.println(json);
            //handlePublic.startLoad(finishWork.this);
            new Thread(() -> CommSelectMethod(Action.action.finishCheckSummitData,json,FCS)).start();
        }
    }

    /**
     * 提交逻辑
     */
    private void SummitData()
    {
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("cMOLotNo",binding.FinishPCNUM.getText().toString());//订单号
        hashMap.put("cMaterialName",fBarcode.cMatName);
        hashMap.put("cSpecifucation",fBarcode.cSpecifucation);//规格
        hashMap.put("cMatNo",fBarcode.cMatNo);
        hashMap.put("cCusName",binding.Custom.getText().toString());
        hashMap.put("cPeriod",binding.Cycle.getText().toString());
        String GNumber = binding.FinishNum.getText().toString();
        String ANumber = binding.buliangshu.getText().toString();
        hashMap.put("GNumber",GNumber);
        hashMap.put("ANumber",ANumber);
        String IMaterialsNum = binding.ComeNum.getText().toString() == "" ? GNumber : binding.ComeNum.getText().toString();
        hashMap.put("IMaterialsNum",IMaterialsNum);
        hashMap.put("cPlace",binding.RuKuTag.getText().toString());//货位
        hashMap.put("warehousecode",binding.RuKuCang.getText().toString());//仓库位置
        String ReportTime = handlePublic.Date(1);
        hashMap.put("ReportTime",ReportTime);//时间
        String json = handlePublic.MakeJson(hashMap);
        System.out.println(json);
        //handlePublic.startLoad(finishWork.this);
        new Thread(() -> CommSelectMethod(Action.action.finishSummitData,json,Summit)).start();
    }

    /**
     *
     * @param message
     */
    private void showUpdateDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(finishWork.this);
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setPositiveButton("是", (dialogInterface, i) -> IsTopSummit = true);
        builder.setNegativeButton("否",
                (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

    /**
     * 数据库查询通用方法
     * @param action //查询Action
     * @param para // 数据
     * @param what //回调后的参数
     */
    private void CommSelectMethod(String action,String para,int what) {
        List BList;
        BList = net_finishWork.CS_CommonMethod(action,para);
        handlePublic.setmHandler(what,BList);
    }

    /**
     * 提空表单
     */
    public void CleanForm()
    {
        binding.LCDFinish.setText("");
        binding.FinishPCNUM.setText("");
        binding.Custom.setText("");
        binding.Cycle.setText("");
        binding.FinishNum.setText("");
        binding.ComeNum.setText("");
        binding.RuKuCang.setText("");
        binding.RuKuTag.setText("");
        IsTopSummit = false;
    }

    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }
}